import classnames from 'classnames'
import { useHistory } from 'react-router'
import { NavBar, SearchBar } from 'antd-mobile'

import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import { getSuggestion } from '@/api/search'

// import debounce from 'lodash/debounce'
// const debounceFn = debounce(async (value, setSuggestList) => {
//   const suggestList = await getSuggestion({ q: value })
//   console.log(suggestList.data.options)
//   setSuggestList(suggestList.data.options)
// }, 500)

import { useDebounceFn } from 'ahooks'
const GEEK_SEARCH_KEY = 'GEEK_SEARCH_KEY'
const SearchPage = () => {
  const history = useHistory()

  const [searchTxt, setSearchTxt] = useState('')
  const [suggestList, setSuggestList] = useState<string[]>([])

  const { run } = useDebounceFn(
    async (value: string) => {
      const suggestList = await getSuggestion({ q: value })
      console.log(suggestList.data.options)
      // 处理高亮
      const newList = suggestList.data.options.map((item) => {
        // return item && item.replaceAll(value, `<span>${value}</span>`)
        return item?.replaceAll(value, `<span>${value}</span>`)
      })
      console.log(newList)
      setSuggestList(newList)
    },
    {
      wait: 500,
    }
  )
  const onSearchChange = async (value: string) => {
    setSearchTxt(value)
    if (!value.trim()) return setSuggestList([])
    // 普通写法
    // const suggestList = await getSuggestion({ q: value })
    // console.log(suggestList.data.options)
    // 1-防抖处理(lodash)
    // debounceFn(value, setSuggestList)
    // 2-防抖处理ahook
    run(value)
  }

  // 跳转结果页
  const goResult = (val: string) => {
    console.log(val)
    if (!val.trim()) return
    // 使用定时器处理跳转后useEffect不执行问题
    setTimeout(() => history.push(`/search/result?q=${val}`))
    // history.push(`/search/result?q=${val}`)
    // 存储搜索记录
    saveHistory(val)
  }

  // 搜索历史记录
  const [historyList, setHistoryList] = useState<string[]>(
    JSON.parse(localStorage.getItem(GEEK_SEARCH_KEY) ?? '[]')
  )
  const saveHistory = (val: string) => {
    if (historyList.some((item) => item === val)) return
    setHistoryList([val, ...historyList])
    console.log('获取不到最新修改数据：', historyList)
  }
  useEffect(() => {
    console.log('存储搜索历史...')
    localStorage.setItem(GEEK_SEARCH_KEY, JSON.stringify(historyList))
  }, [historyList])

  // 操作历史记录
  const delHistory = (val: string) => {
    setHistoryList(historyList.filter((item) => item !== val))
  }
  const clearHistory = () => {
    setHistoryList([])
  }

  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span onClick={() => goResult(searchTxt)} className="search-text">
            搜索
          </span>
        }>
        <SearchBar
          placeholder="请输入关键字搜索"
          value={searchTxt}
          onChange={onSearchChange}
          onSearch={goResult}
        />
      </NavBar>
      {/* 搜索历史记录 */}
      {/* 联想词列表无数据才展示历史记录 */}
      {suggestList.length === 0 && historyList.length > 0 && (
        <div className="history">
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={clearHistory}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {historyList.map((item) => (
              <span
                key={item}
                className="history-item"
                onClick={() => history.push(`/search/result?q=${item}`)}>
                <span className="text-overflow">{item}</span>
                <Icon
                  onClick={(e) => {
                    e.stopPropagation()
                    delHistory(item)
                  }}
                  type="iconbtn_essay_close"
                />
              </span>
            ))}
          </div>
        </div>
      )}
      {/* 联想关键词 */}
      <div
        className={classnames(
          'search-result',
          suggestList.length ? 'show' : ''
        )}>
        {suggestList.map(
          (item, i) =>
            item && (
              <div className="result-item" key={i}>
                <Icon className="icon-search" type="iconbtn_search" />
                <div
                  className="result-value text-overflow"
                  onClick={() =>
                    goResult(
                      item.replaceAll(`<span>${searchTxt}</span>`, searchTxt)
                    )
                  }
                  dangerouslySetInnerHTML={{ __html: item }}>
                  {/* <span>黑马</span> */}
                  {/* {item} */}
                </div>
              </div>
            )
        )}
      </div>
    </div>
  )
}

export default SearchPage
